package com.hbx.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hbx.eduservice.entity.EduSubject;
import com.hbx.eduservice.entity.excel.SubjectData;
import com.hbx.eduservice.service.EduSubjectService;
import com.hbx.servicebase.exceptionhandler.GuliException;


/**
 * 用easyExcel必须要用监听器
 * @Author hbx
 * @Date 2023/10/1 16:44
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

   //因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    // 不能实现数据库操作
    public EduSubjectService eduSubjectService;

    public SubjectExcelListener(){}
    public SubjectExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
       if(subjectData == null){
        new GuliException(20001,"文件数据为空");
       }

       //一行一行读取，每次有两个值，一级分类和二级分类
       EduSubject existOneSubject = this.existOneSubject(eduSubjectService, subjectData.getOneSubjectName());
       if(existOneSubject == null){
          existOneSubject = new EduSubject();
          existOneSubject.setParentId("0");
          existOneSubject.setTitle(subjectData.getOneSubjectName());
          eduSubjectService.save(existOneSubject);
       }

        String pid = existOneSubject.getId();
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService, subjectData.getTwoSubjectName(), pid);
        if(existTwoSubject == null){
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(existTwoSubject);
        }
    }

    public EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
       LambdaQueryWrapper<EduSubject> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.like(EduSubject::getTitle,name);
       queryWrapper.eq(EduSubject::getParentId,"0");
       return eduSubjectService.getOne(queryWrapper);
    }

    public EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
       LambdaQueryWrapper<EduSubject> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.like(EduSubject::getTitle,name);
       queryWrapper.eq(EduSubject::getParentId,pid);
       return eduSubjectService.getOne(queryWrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
